package com.ruoyi.system.basicInformation.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.exception.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.system.basicInformation.bo.TTerminalMileageAddBo;
import com.ruoyi.system.mobile.domain.PatrolRecord;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.pagehelper.Page;
import com.ruoyi.system.basicInformation.bo.TTerminalAddBo;
import com.ruoyi.system.basicInformation.bo.TTerminalQueryBo;
import com.ruoyi.system.basicInformation.bo.TTerminalEditBo;
import com.ruoyi.system.basicInformation.domain.TTerminal;
import com.ruoyi.system.basicInformation.mapper.TTerminalMapper;
import com.ruoyi.system.basicInformation.vo.TTerminalVo;
import com.ruoyi.system.basicInformation.service.ITTerminalService;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 终端注册Service业务层处理
 *
 * @author ruoyi
 * @date 2021-05-21
 */
@Service
public class TTerminalServiceImpl extends ServiceImpl<TTerminalMapper, TTerminal> implements ITTerminalService {

    @Override
    public TTerminalVo queryById(Long id) {
        TTerminal db = this.baseMapper.selectById(id);
        return BeanUtil.toBean(db, TTerminalVo.class);
    }

    @Override
    public TTerminalVo queryByTerminalId(String terminalId) {
        TTerminal db = this.baseMapper.selectById(terminalId);
        return BeanUtil.toBean(db, TTerminalVo.class);
    }

    @Override
    public List<TTerminalVo> queryList(TTerminalQueryBo bo) {
//        LambdaQueryWrapper<TTerminal> lqw = Wrappers.lambdaQuery();
//        lqw.like(StrUtil.isNotBlank(bo.getEquipmentName()), TTerminal::getEquipmentName, bo.getEquipmentName());
//        lqw.like(StrUtil.isNotBlank(bo.getEquipmentNumber()), TTerminal::getEquipmentNumber, bo.getEquipmentNumber());
//        lqw.eq(StrUtil.isNotBlank(bo.getTerminalType()), TTerminal::getTerminalType, bo.getTerminalType());
//        lqw.eq(StrUtil.isNotBlank(bo.getState()), TTerminal::getState, bo.getState());
//        return entity2Vo(this.list(lqw));
        return this.baseMapper.selectDTO(bo);
    }

    /**
     * 实体类转化成视图对象
     *
     * @param collection 实体类集合
     * @return
     */
    private List<TTerminalVo> entity2Vo(Collection<TTerminal> collection) {
        List<TTerminalVo> voList = collection.stream()
                .map(any -> BeanUtil.toBean(any, TTerminalVo.class))
                .collect(Collectors.toList());
        if (collection instanceof Page) {
            Page<TTerminal> page = (Page<TTerminal>) collection;
            Page<TTerminalVo> pageVo = new Page<>();
            BeanUtil.copyProperties(page, pageVo);
            pageVo.addAll(voList);
            voList = pageVo;
        }
        return voList;
    }

    @Override
    public List<TTerminalVo> terminalInlineStatistics(TTerminalQueryBo bo) {
//        List<TTerminalVo> tTerminalVoList = this.baseMapper.terminalInlineStatistics(bo);

        if (!SecurityUtils.getLoginUser().getUser().getUserType().equals("00")) {
            if (SecurityUtils.getLoginUser().getUser().getDept().getDeptId() != null) {
                bo.setDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                return this.baseMapper.terminalInlineStatistics(bo);
            } else return null;
        } else {
            return this.baseMapper.terminalInlineStatistics(bo);
        }

//        for (TTerminalVo str : tTerminalVoList) {
//            TTerminalQueryBo tTerminalQueryBo = new TTerminalQueryBo();
//            tTerminalQueryBo.setId(str.getShipId());
//            if ("1".equals(str.getShipType()))
//                str.setChildren(this.baseMapper.terminalInlineChildrenStatisticsY(tTerminalQueryBo));
//            else
//                str.setChildren(this.baseMapper.terminalInlineChildrenStatistics(tTerminalQueryBo));
//        }
//        return tTerminalVoList;
    }

    @Override
    public TTerminal checkIsExists(String equipmentNumber) {

        QueryWrapper<TTerminal> queryWrapper = new QueryWrapper();
        queryWrapper.lambda().eq(TTerminal::getEquipmentNumber, equipmentNumber);
        queryWrapper.lambda().eq(TTerminal::getDelFlag, "0");

        return this.baseMapper.selectOne(queryWrapper);
    }

    @Override
    public void updateTerminalByObjId(Long id, Long objId) {
        this.baseMapper.updateTerminalByObjId(id, objId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean unBundling(Long terminalId) {
        boolean save = false;
        try {
            save = this.baseMapper.updateTerminalByObjId(terminalId, null) > 0;

        } catch (Exception e) {
            e.printStackTrace();
            throw new BaseException("解绑终端设备失败");
        }
        return save;
    }

    @Override
    public List<TTerminalVo> terminalOnlineRate(TTerminalQueryBo bo) {
        if (!SecurityUtils.getLoginUser().getUser().getUserType().equals("00"))
        {
            if(SecurityUtils.getLoginUser().getUser().getDept().getDeptId() != null){
                bo.setDeptId(SecurityUtils.getLoginUser().getUser().getDept().getDeptId());
                return this.baseMapper.terminalOnlineRate(bo);
            }
            else return null;
        }else {
            return this.baseMapper.terminalOnlineRate(bo);
        }
    }

    @Override
    public List<TTerminalVo> terminalInlineChildrenStatistics(TTerminalQueryBo bo) {
        if ("1".equals(bo.getShipType()))
            return this.baseMapper.terminalInlineChildrenStatisticsY(bo);
        else
            return this.baseMapper.terminalInlineChildrenStatistics(bo);
    }

    @Override
    public Boolean insertByAddBo(TTerminalAddBo bo) {
        TTerminal add = BeanUtil.toBean(bo, TTerminal.class);
        validEntityBeforeSave(add);
        return this.save(add);
    }

    @Override
    public Boolean insertTaskByAddBo(TTerminalAddBo bo) {
        return this.baseMapper.insertTaskByAddBo(bo) > 0;
    }

    @Override
    public Boolean updateByEditBo(TTerminalEditBo bo) {
        TTerminal update = BeanUtil.toBean(bo, TTerminal.class);
        validEntityBeforeSave(update);
        return this.updateById(update);
    }

    @Override
    public Boolean updateByEditTTerminal(TTerminal bo) {
        return this.updateById(bo);
    }

    @Override
    public Boolean insertMileage(TTerminalMileageAddBo bo) {
        return this.baseMapper.insertMileage(bo) > 0;
    }

    @Override
    public void deleteTerminalOnline() {
         this.baseMapper.deleteTerminalOnline();
    }

    @Override
    public void insertTerminalOnline() {
         this.baseMapper.insertTerminalOnline();
    }

    @Override
    public List<TTerminalVo> listTouristCurrentPoint() {
        Long areaId = null;
        if (SecurityUtils.getLoginUser().getUser().getAreaId() != 1)
            areaId = SecurityUtils.getLoginUser().getUser().getAreaId() > 0 ? SecurityUtils.getLoginUser().getUser().getAreaId() : 0;
        return this.baseMapper.listTouristCurrentPoint(areaId);
    }

    /**
     * 保存前的数据校验
     *
     * @param entity 实体类数据
     */
    private void validEntityBeforeSave(TTerminal entity) {
        //TODO 做一些数据校验,如唯一约束
    }

    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if (isValid) {
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return this.removeByIds(ids);
    }
}
